package com.example.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.system.common.Result;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.example.system.entity.Params;
import com.example.system.entity.User;
import com.example.system.exception.CustomException;
import com.example.system.mapper.UserMapper;
import com.example.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hjw
 * @since 2024-01-23
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;

    public int deleteById(Integer id) {
        return userMapper.deleteById(id);
    }

    public boolean existsUserById(Integer id){
        return userMapper.existsUserById(id);
    }

    public PageInfo<User> findPageByUserName(Params params) {
        //在service里做分页查询的逻辑处理
        try {
            PageHelper.startPage(params.getPageNum(), params.getPageSize());
        } catch (Exception e) {
            throw new CustomException("无法启动页面帮助器");
        }
        //接下来的查询会自动按照 当前开启的分页设置。
        List<User> userList = userMapper.findPageByUserName(params);
        return PageInfo.of(userList);
    }

    public void add(User user) {
        //用户名一定要有不能为空
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new CustomException("用户名不能为空");
        }
        //1.进行重复性判断，同名字的管理员不允许新增
        User isExist = userMapper.findByFullUserName(user.getUsername());
        if (isExist != null) {
            //说明用户名已存在，要提示前台
            throw new CustomException("该用户名已存在，请勿重复");
            //add函数返回void,为了提示前台，设置全局异常处理，让异常返回msg
        }
        //初始化一个密码
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword("123456");
        }
        userMapper.insertSelective(user);
    }

    public void update(User user) {
        User usedUser = userMapper.findByUserID(user.getId());
        if (!user.getUsername().equals(usedUser.getUsername())) {
            throw new CustomException("当前请求修改的用户与原用户的用户名不同");
        }
        if (user.getNickname() == null || user.getNickname().isEmpty()) {
            user.setNickname(usedUser.getNickname());
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            user.setPassword(usedUser.getPassword());
        }
        userMapper.updateById(user);
    }

    public User login(User user) {
        //1.进行非空判断，用户名密码是否为空，可以在前后台，这里在后台
        //用户名一定要有不能为空
        if (user.getUsername() == null || user.getUsername().isEmpty()) {
            throw new CustomException("用户名不能为空");
        }
        if (user.getPassword() == null || user.getPassword().isEmpty()) {
            throw new CustomException("密码不能为空");
        }
        //2.从数据库里根据用户名和密码，查询对应的用户
        User loginUser = userMapper.findByNameAndPwd(user.getUsername(), user.getPassword());
        if (loginUser == null) {
            //如果查失败，说明用户名或密码有误，提醒用户
            throw new CustomException("用户名或密码错误");
        }
        //如果查成功，说明有该管理员，用户名密码都对
        return loginUser;
    }

    public User findSelfInfoByUserID(Integer id) {
        return userMapper.findSelfInfoByUserID(id);
    }

    public List<User> findFamilyMemberByUserID(Integer id) {
        return userMapper.findFamilyMemberByUserID(id);
    }

    public void addNewFamilyMember(Integer curUserID, Integer familyMemberID) {
        if (curUserID.equals(familyMemberID)) {
            throw new CustomException("不可邀请自己");
        }
        User curUser = this.findSelfInfoByUserID(curUserID);
        if (curUser == null) {
            throw new CustomException("当前用户不存在");
        }
        User familyMember = this.findSelfInfoByUserID(familyMemberID);
        if (familyMember == null) {
            throw new CustomException("被邀请的家庭成员不存在");
        }
        boolean ifExit = (
                userMapper.existsFamilyMemberPair(curUserID, familyMemberID) &&
                        userMapper.existsFamilyMemberPair(familyMemberID, curUserID)
        );
        if (!ifExit) {
            userMapper.addNewFamilyMember(curUserID, familyMemberID);
            userMapper.addNewFamilyMember(familyMemberID, curUserID);
        } else {
            throw new CustomException("当前用户已邀请过此家庭成员");
        }
    }

    public void deleteFamilyMember(Integer curUserID, Integer familyMemberID) {
        if (curUserID.equals(familyMemberID)) {
            throw new CustomException("自己不是自己的家庭成员");
        }
        User curUser = this.findSelfInfoByUserID(curUserID);
        if (curUser == null) {
            throw new CustomException("当前用户不存在");
        }
        User familyMember = this.findSelfInfoByUserID(familyMemberID);
        if (familyMember == null) {
            throw new CustomException("所需移除的用户不存在");
        }
        boolean ifExit = (
                userMapper.existsFamilyMemberPair(curUserID, familyMemberID) &&
                        userMapper.existsFamilyMemberPair(familyMemberID, curUserID)
        );
        if (ifExit) {
            userMapper.deleteFamilyMember(curUserID, familyMemberID);
            userMapper.deleteFamilyMember(familyMemberID, curUserID);
        } else {
            throw new CustomException("当前用户无此家庭成员");
        }
    }

    public List<User> findFamilyMemberByUserIdAndFamilyMemberId(Integer userId, Integer familyMemberId) {
        User curUser = this.findSelfInfoByUserID(userId);
        if (curUser == null) {
            throw new CustomException("当前用户不存在");
        }
        User familyMember = this.findSelfInfoByUserID(familyMemberId);
        if (familyMember == null) {
            throw new CustomException("要查询的家庭成员不存在");
        }
        if (!userMapper.existsFamilyMemberPair(userId, familyMemberId)) {
            throw new CustomException("当前用户无id为" + familyMemberId + "的家庭成员");
        }
        User ansUser = this.findSelfInfoByUserID(familyMemberId);
        if (ansUser == null) {
            throw new CustomException("未找到id为" + familyMemberId + "的家庭成员");
        }
        List<User> ans = new ArrayList<>();
        ans.add(this.findSelfInfoByUserID(familyMemberId));
        return ans;
    }
}
